/*
 * MIT License
 *
 * Copyright (c) 2020 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package cn.seaboot.postman;

import cn.seaboot.common.core.CommonUtils;
import cn.seaboot.common.exception.BizException;
import cn.seaboot.postman.root.Info;
import cn.seaboot.postman.root.Item;
import cn.seaboot.postman.root.Postman;
import cn.seaboot.postman.root.Variable;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 采用fluent写法的Postman构建工具
 *
 * @author Mr.css
 * @date 2020-01-28 11:46
 */
public class PostmanBuilder {
    private Postman postman = new Postman();
    private ApiLoader loader = new ApiLoader();
    private List<Item> res = new ArrayList<>();

    /**
     * Create PostmanBuilder instance by Configuration
     *
     * @param configuration PostmanConfiguration
     * @return PostmanBuilder
     */
    public static PostmanBuilder create(PostmanConfiguration configuration) {
        PostmanBuilder builder = new PostmanBuilder();
        builder.loader.setConfiguration(configuration);

        //如果未指定API的唯一ID，则手动生成一个
        String postmanId = configuration.getPostmanId();
        if (postmanId == null) {
            postmanId = UUID.randomUUID().toString();
        }

        //构建Info节点
        Info info = new Info();
        info.set_postman_id(postmanId);
        info.setName(configuration.getApiName());
        info.setSchema(configuration.getPostmanVersion());
        builder.postman.setInfo(info);

        //构建一个Variable节点，设置一个共享变量，全局的URL都通过占位符实现
        String[] hosts = configuration.getHost();
        if (CommonUtils.isEmpty(hosts)) {
            throw new BizException("OpenAPI hosts is undefined!");
        }
        configuration.setHost(new String[]{"{{baseUrl}}"});
        Variable variable = new Variable();
        variable.setId("baseUrl");
        variable.setKey("baseUrl");
        variable.setType("string");
        variable.setValue(hosts[0]);
        builder.postman.setVariable(new Variable[]{variable});
        return builder;
    }

    /**
     * search api by ApplicationContext
     *
     * @param context ApplicationContext
     * @return PostmanBuilder
     */
    public PostmanBuilder searchApi(ApplicationContext context) {
        //扫描所有的Controller
        Map<String, Object> controllers = context.getBeansWithAnnotation(Controller.class);
        if (CommonUtils.isNotEmpty(controllers)) {
            for (Object controller : controllers.values()) {
                this.searchApi(controller.getClass());
            }
        }
        //扫描所有的RestController
        controllers = context.getBeansWithAnnotation(RestController.class);
        if (CommonUtils.isNotEmpty(controllers)) {
            for (Object controller : controllers.values()) {
                this.searchApi(controller.getClass());
            }
        }
        return this;
    }

    /**
     * search api by a Class
     *
     * @param clazz Controller's Class
     * @return PostmanBuilder
     */
    public PostmanBuilder searchApi(Class<?> clazz) {
        List<Item> item = loader.searchApi(clazz);
        if (item != null) {
            res.addAll(item);
        }
        return this;
    }

    /**
     * return Postman node
     *
     * @return Postman
     */
    public Postman build() {
        postman.setItem(res.toArray(new Item[]{}));
        return postman;
    }

    //getter/setter---------------------------------------------------

    public PostmanBuilder setVariable(Variable variable) {
        postman.setVariable(new Variable[]{variable});
        return this;
    }

    public PostmanBuilder setInfo(Info variable) {
        postman.setInfo(variable);
        return this;
    }

    public PostmanBuilder addItem(List<Item> item) {
        postman.setItem(item.toArray(new Item[]{}));
        return this;
    }
}
